<?php

namespace Admin\Controller;
use Think\Controller;
use Admin\Controller\AdminController;
use Org\Util\Wechat;
/**
 * 菜单模块
 */

class BuyerController extends AdminController{
	private $curPeriod;
    public function _initialize(){
        parent::_initialize();
        // 获取当前准备期或进行期的期数内容
        $condition = array();
        $condition['status'] = array(array('eq',C('p_status_ready')),array('eq',C('p_status_go')), 'or') ;
    	$this->curPeriod = M('period')->where($condition)->find();
    	
    	// 检查用户权限
    	$chkUsrPrilgRes = checkUserPrivilege();
		if($chkUsrPrilgRes[0]) {
			$this->error($chkUsrPrilgRes[1]);
		}
    }

    public function showUsers() {
		
		if(IS_POST) {
			// 如果keyword是通过POST过来，即form提交过来
			$keyword = I('post.keyword');
			\Think\Log::write("关键词 => " . $keyword);
			$users = $this->searchUser4ShowUsers($keyword);
			$this->assign("users", $users);
			$this->assign("keyword", $keyword);
			
			$this->display();
		} else {
			// 如果keyword是通过GET过来，即分页链接
			$keyword = I('get.keyword');
			if(!empty($keyword)) {
				$users = $this->searchUser4ShowUsers($keyword);
				$this->assign('users', $users);
			} else {
				// 如果首次进入，显示所有用户
				$user_m = M("wxuser"); 
		        $count = count($user_m->select());
		        $Page  = new \Think\Page($count,30);
		        $show  = $Page->show();
		        
		        $users = $user_m->limit($Page->firstRow.','.$Page->listRows)->select();
		                
		        $this->assign('users', $users);
		        $this->assign('Page', $show);
			}
			$this->display();
		}
    }
    
    public function addUser() {
	    if(IS_POST) {
		    $data_1 = array();
		    $data_1['nickname'] 		= I('nickname');
		    $data_1['colid'] 			= 'A';
		    $data_1['basketid'] 		= trim(I('basketid'));
		    $data_1['discount_money'] 	= I('discount_money');
		    $data_1['truename'] 		= trim(I('truename'));
		    $data_1['address'] 			= trim(I('address'));
		    $data_1['tell'] 			= trim(I('tell'));
		    
		    $res = M('wxuser')->add($data_1);
		    if($res) {
			    $this->success('保存成功!');
		    } else {
			    $this->error('保存失败,请检查');
		    }
	    } else {
		    $this->display();
	    }
    }
    
    public function editUser() {
	    $uid = I('id');
	    
	    if(IS_POST) {
		    if(empty($uid)) {
			    $this->error('保存失败，无用户编号!');
			    exit;
		    }
		    $data_1 = array();
		    $data_1['colid'] = trim(I('colid'));
		    $data_1['basketid'] = trim(I('basketid'));
		    
		    $data_1['truename'] = trim(I('truename'));
		    $data_1['address'] = trim(I('address'));
		    $data_1['tell'] = trim(I('tell'));
		    
		    $condition_1 = array('id' => $uid);
		    $res = M('wxuser')->where($condition_1)->save($data_1);
		    if($res) {
			    $this->success('保存成功!');
		    } else {
			    $this->error('保存失败,请检查');
		    }
		    exit;
	    } else {
		    if(empty($uid)) {
			    $this->error('编辑用户出错，无用户编号!');
			    exit;
		    }
		    $user = M('wxuser')->where(array('id' => $uid))->find();
		    $this->assign('user', $user);
		    
		    $this->display();
	    }
    }
    
    public function updateUserInfo() {
	    $openid = trim(I('id'));
	    if(empty($openid)) {echo "无openid"; exit;}
	    
	    $weObj = new Wechat();
		$wxuser = $weObj->getUserInfo($openid);
		if($wxuser != false) {
			if($wxuser['subscribe'] == 0) {
				echo "该用户已经取消关注!";
				exit;
			}
			$data_1 = array();
			$data_1['nickname'] = $wxuser['nickname'];
			$data_1['headimgurl'] = $wxuser['headimgurl'];
			
			$condition_1 = array('openid' => $openid);
			
			$res = M('wxuser')->where($condition_1)->save($data_1);
			echo json_encode($wxuser);
		} else {
			echo "获取出错！"; exit;
		}
		exit;
    }
    
    
    public function uploadImage2Wechat() {
    	$data = null;
    	if (class_exists('\CURLFile')) {
			$data = array('media' => new \CURLFile('/www/web/9mu/public_html/Public/Upload/OA.jpg'));
		} else {
			$data = array('media' => '@/www/web/9mu/public_html/Public/Upload/OA.jpg');
		}
    	
	    //$data = array("media" => '@/www/web/9mu/public_html/Public/Upload/OA.jpg');
	    $weObj = new Wechat();
		$res = $weObj->uploadMedia($data, 'image');
		exit;
    }
    
    public function synchWXUser() {
	    $next_openid = '';
	    $weObj = new Wechat();
		do {
	    	$openidList = $weObj->getUserList($next_openid);
	    	
	    	foreach($openidList['data']['openid'] as $openid) {
	    		$user = $weObj->getUserInfo($openid);
	    		$tmpStr = json_encode($user['nickname']); //暴露出unicode
			    $tmpStr = preg_replace("#(\\\u[d-e][0-9a-f]{3})#ie","",$tmpStr); //将emoji的unicode留下，其他不动
			    $nicknametmp = json_decode($tmpStr);
	    		$data_1 = array(
	    			'nickname' 	=> $nicknametmp,
	    			'sex'		=> $user['sex'],
	    			'province'	=> $user['city'],
	    			'headimgurl'=> $user['headimgurl'],
	    			'subscribe_time'	=> $user['subscribe_time'],
	    			'status'	=> 1	// 订阅
	    		);
	    		$existUser = M('wxuser')->where(array('openid' => $user['openid']))->find();
	    		if($existUser) {
		    		// 更新用户信息
		    		M('wxuser')->where(array('openid' => $user['openid']))->save($data_1);
	    		} else {
		    		// 插入新用户
		    		$data_1['openid'] = $user['openid'];
		    		M('wxuser')->add($data_1);
	    		}
	    	}
	    	if($openidList['next_openid']!='') {
		    	$next_openid = $openidList['next_openid'];
	    	} else {
		    	$next_openid = '';
	    	}
    	}while($next_openid != '');
    	$result = array();
    	$result['code'] = 0;
    	$result['result'] = 'OK';
    	$this->ajaxReturn($result);
    }
    
    /*
	 *	用户分组
	 */
	public function showUserGroup() {
		$groups = M('group')->order('sortid ASC')->select();

		$this->assign('groups', $groups);
		
		$this->display();
	}
	
	public function addUserGroup() {
		$gid = I('gid');
		if(IS_POST) {
			$data_0 = array();
			$data_0['grpname'] = I('gname');
			$data_0['create_time'] = time();
			$data_0['sortid'] = I('sortid');
			if(!empty($gid)) {
				$condition_0 = array('id'=>$gid);
				$res = M('group')->where($condition_0)->save($data_0);
			}else {
				$res = M('group')->add($data_0);
			}
			if($res) {
				$this->success("更新成功");
			} else {
				$this->error("更新失败");
			}
		} else {
			if(!empty($gid)) {
			$group = M('group')->where(array('id' => $gid))->find();
			}
			
			$this->assign('group', $group);
			$this->display();
		}
	}
	
	public function useGroup() {
		$gid = I('gid');
		
		// 取消其他用户组
		// $condition_0 = array('is_use' => 1);
		// $data_0 = array('is_use' => 0);
		// $res0 = M('group')->where($condition_0)->save($data_0);

		// 设置当前为启用
		$condition_1 = array('id' => $gid);
		$data = M('group')->field('is_use')->where($condition_1)->find();
		if($data['is_use'] == 0){
			$data_1 = array('is_use' => 1);	
		}else{
			$data_1 = array('is_use' => 0);
		}
		
		$res1 = M('group')->where($condition_1)->save($data_1);
		// if($res0 && $res1) {
		if($res1) {
			$this->success("设置成功");
		} else {
			$this->error("设置失败");
		}
	}
	
	public function showGrpUsers() {
		import("ORG.Util.Page");
		
		$gid = I('gid');
		$usrgrp_m = M('user_group');
		
		$condition_0 = array('gid' => $gid);
		$count = count($usrgrp_m->where($condition_0)->select());
		$Page = new \Think\Page($count, 5);
		$show = $Page->show();
		
		$users = $usrgrp_m
			->alias('a')
			->join('__WXUSER__ as b ON b.basketid = a.basketid')
			->order('add_time ASC')
			->where($condition_0)
			->limit($Page->firstRow.','.$Page->listRows)
			->select();
		$this->assign('gid', $gid);
		$this->assign('page', $show);
		$this->assign('users', $users);
		
		$this->display();
	}
	
	public function delGrpUser() {
		$gid = I('gid');
		$basketid = I('basketid');
		$condition_0 = array('gid' => $gid, 'basketid' => $basketid);
		$res = M('user_group')->where($condition_0)->delete();
		
		if($res) {
			$this->success("删除用户成功");
		} else {
			$this->error("删除用户失败");
		}
	}
	
	public function add_user2grp() {
		$gid 		= I('get.gid');
		$openid 	= I('post.openid');
		$basketid 	= I('post.basketid');
		if(empty($basketid) || $basketid == '') {
			$result['result'] = "该用户无菜篮子号，非套餐用户，添加失败!";
			$result['code'] = 0;
		} else {
			$data_0 = array();
			$data_0['gid'] = $gid;
			if(!empty($openid)) {
				$data_0['openid'] = $openid;
			}
			$data_0['basketid'] = $basketid;
			$data_0['add_time'] = time();
			$res = M('user_group')->add($data_0);
			if($res) {
				$result['result'] = "将用户加入用户组-成功";
				$result['code'] = 1;
			} else {
				$result['result'] = "将用户加入用户组-失败";
				$result['code'] = 0;
			}
		}
		$this->ajaxreturn($result);
	}
	
	public function del_user2grp() {
		$gid 	= I('get.gid');
		$openid = I('post.openid');
		
		$condition_0 = array();
		$condition_0['gid'] = $gid;
		$condition_0['openid'] = $openid;
		$res = M('user_group')->where($condition_0)->delete();
		
		if($res) {
			$result['result'] = "将用户删除-成功";
			$result['code'] = 1;
		} else {
			$result['result'] = "将用户删除-失败";
			$result['code'] = 0;
		}
		
		$this->ajaxreturn($result);
	}
	// 添加用户
	public function addUser2Grp() {
		$gid = I('get.gid');
		
		$this->assign('gid', $gid);
		$condition_0 = array("gid" => $gid);
		
		if(IS_POST) {
			// 如果keyword是通过POST过来，即form提交过来
			$keyword = I('post.keyword');
			$users = $this->searchUsr4Grp($keyword, $gid);
			$this->assign("users", $users);
			$this->assign("keyword", $keyword);
			
			$this->display();
		} else {
			// 如果keyword是通过GET过来，即分页链接
			$keyword = I('get.keyword');
			if(!empty($keyword)) {
				$users = $this->searchUsr4Grp($keyword, $gid);
				$this->assign('users', $users);
			}
			$this->display();
		}
	}
	
	private function searchUsr4Grp($keyword, $gid) {
		import("ORG.Util.Page");
		$condition_0 = array();
		if(!empty($keyword)) {
			$condition_0['a.nickname'] 	= array('like', "%$keyword%");
			$condition_0['a.truename'] 	= array('like', "%$keyword%");
			$condition_0['_logic']		= 'OR';
		}
		
		$model = M();
		$subQuery = $model->table("tp_user_group")->where(array("gid" => $gid))->select(false);
		
		$count = M("wxuser")
		->alias('a')
		->join("LEFT JOIN (" . $subQuery . ") c ON a.basketid = c.basketid")
		->where($condition_0)
		->count();
		$Page = new \Think\Page($count, 5);
		
		$users = M("wxuser")
		->alias('a')
		->join("LEFT JOIN (" . $subQuery . ") c ON a.basketid = c.basketid")
		->where($condition_0)
		->limit($Page->firstRow.','.$Page->listRows)
		->order('a.subscribe_time desc')
		->getField('a.id as aid, a.openid as aopenid, a.basketid as abasketid,  a.nickname as anickname, a.truename as atruename, c.gid as cgid, a.subscribe_time as asubscribe_time');
		\Think\Log::write();
		$show = $Page->show();
		$this->assign("Page", $show);
		
		return $users;
	}
	
	private function searchUser4ShowUsers($keyword) {
		import("ORG.Util.Page");
		$condition_0 = array();
		if(!empty($keyword)) {
			$condition_0['a.nickname'] = array('like', "%$keyword%");
			$condition_0['a.truename'] = array('like', "%$keyword%");
			$condition_0['_logic']	   = 'OR';
		}
		
		$count = M("wxuser")
			->alias('a')
			->where($condition_0)
			->count();
		
		$Page = new \Think\Page($count, 30);
		
		$users = M("wxuser")
			->alias('a')
			->where($condition_0)
			->limit($Page->firstRow.','.$Page->listRows)
			->order('a.subscribe_time desc')
			->select();
			
		$show = $Page->show();
		$this->assign("Page", $show);
		
		return $users;
	}
	
	public function getOneUserInfo() {
		$basketid = I('post.basketid');
		$userinfo = M('wxuser')->where(array('basketid' => $basketid))->find();
		$result = array();
		if($userinfo) {
			$result['truename'] = $userinfo['truename'];
			$result['tell']		= $userinfo['tell'];
			$result['address']	= $userinfo['address'];
			$result['code']		= 1;
		}else {
			$result['result']	= '无此用户';
			$result['code']		= 0;
		}
		 
		$this->ajaxReturn($result);
	}
	
	public function bandUser() {
		$basketid 	= I('basketid');
		$uid 		= I('id');
		
		// 获取套餐用户的4大原始信息，基于微信用户信息更新这个用户的信息，好绕
		$ouser = M('wxuser')->where(array('basketid' => $basketid))->find();
		$data = array();
		$data['colid'] = 'A';
		$data['truename'] 	= $ouser['truename'];
		$data['tell']		= $ouser['tell'];
		$data['address']	= $ouser['address'];
		$data['basketid']	= $basketid;
		$data['discount_money']	= $ouser['discount_money'];
		$condition = array('id' => $uid);
		
		$res = M('wxuser')->where($condition)->save($data);
		// 获取该用户的微信用户信息
		$wxuser = M('wxuser')->where(array('id' => $uid))->find();
		
		// 更新用户分组表中用户的openid
		M('user_group')->where(array('basketid' => $basketid))->save(array('openid' => $wxuser['openid']));
		
		if($res) {
			// 删除原始用户信息
			M('wxuser')->where(array('id' => $ouser['id']))->delete();
			$this->success("绑定成功");
		}else {
			$this->error('绑定失败');
		}
	}
	
	public function showPushMsgStatus() {
		if($this->curPeriod) {
			$period = $this->curPeriod['periodid'];
			$periodName = $this->curPeriod['pname'];
			$periodTName = $this->curPeriod['ppname'];
			$periodING = true;
		} else {
			// 查询出刚关闭的一期
			$condition_1['doGeneral'] = array('eq', 1);
			$condition_1['status'] = array('eq', 3);
			$lastPeriod = M('period')->where($condition_1)->order('endtime desc')->limit(1)->select();
	        $period = $lastPeriod[0]['periodid'];
	        $periodTName = $lastPeriod[0]['ppname'];
	        $periodName = $lastPeriod[0]['pname'];
		}
		
		$this->assign('opid', $period);
		$this->assign('ppname', $periodTName);
		
		// 当前用户组
		$curGroup = M('group')->where('`is_use` = 1')->find();
		$curGroupid = $curGroup['id'];
		$pushMsgUsers = M('user_group')
			->alias('a')
			->join('__WXUSER__ as b ON b.openid = a.openid')
			->where("a.`gid` = '$curGroupid' and a.`openid` is not null")
			->getField('a.openid as openid, b.opid as opid, b.pushmsgresult as pushmsgresult, b.basketid as basketid, b.nickname as nickname, b.truename as truename');
		
		foreach($pushMsgUsers as $key => $user) {
			if($user['opid'] != $period) {
				$pushMsgUsers[$key]['pushmsgresult'] = '期数错误';
			} else {
				if($user['pushmsgresult'] == 'success') {
					$pushMsgUsers[$key]['pushmsgresult'] = '消息已送达';
				} else {
					$pushMsgUsers[$key]['pushmsgresult'] = '消息未送达';
				}
			}
			
		}
		
		$this->assign('pushMsgUsers', $pushMsgUsers);
		
		$this->display();
	}
	
	public function repushMsg(){
		$openid = I('openid');
		$user = M('wxuser')->where(array('openid' => $openid))->find();
		
		if($this->curPeriod) {
			$period = $this->curPeriod;
			$periodING = true;
		} else {
			// 查询出刚关闭的一期
			$condition_1['doGeneral'] = array('eq', 1);
			$condition_1['status'] = array('eq', 3);
			$lastPeriod = M('period')->where($condition_1)->order('endtime desc')->limit(1)->select();
	        $period = $lastPeriod[0];
		}
		
		$result = pushWXTplMsg($openid, $user['nickname'],$period, true);
		
		if($result['result_code'] == 1) {
			$this->success($result['result_msg']);
		} else {
			$this->error($result['result_msg']);
		}
	}
}


